package com.cloudea.lotus.action;

import com.cloudea.lotus.Request;
import com.cloudea.lotus.Response;
import com.cloudea.lotus.bo.UserInfo;
import com.cloudea.lotus.dao.DAO;
import com.cloudea.lotus.utils.JWTUtil;

public class LotusActionLogin implements LotusAction {

    @Override
    public Response done(Request request, DAO dao) {
        String account = request.getParameter("account");
        String password = request.getParameter("password");
        String expire = request.getParameter("expire");

        if(account == null && password != null || account != null && password == null){
            return Response.fail("请输入完整的账号密码");
        }

        long expireTime = 0;
        try {
            expireTime = Long.parseLong(expire);
        }catch (NumberFormatException e){
            return Response.fail("expire没有指定或格式不正确");
        }

        if(expireTime < 0){
            return Response.fail("expire不能小于0");
        }

        if(expireTime > 2592000000L){
            return Response.fail("expire不能大于30天的毫秒数");
        }

        UserInfo userInfo = dao.login(account, password);
        if(userInfo == null){
            return Response.fail("账号或密码错误");
        }

        String jwt = JWTUtil.generate(userInfo, expireTime);
        return Response.success(jwt);
    }

    @Override
    public String getName() {
        return "login";
    }
}
